package com.mxx.common.netty.http;


import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import io.netty.buffer.UnpooledHeapByteBuf;
import io.netty.handler.codec.http.multipart.FileUpload;


import java.io.*;
import java.nio.channels.FileChannel;

/**
 * @Auther: Mr. Zeng
 * @Date: 2020/8/14 22:56
 * @Description: 暂无描述
 */
public class NettyMultipartFile {

    public static void writeFile(FileUpload fileUpload, String filePath) throws com.mxx.common.exception.IOException {
        writeFile(fileUpload, new File(filePath));
    }

    public static void writeFile(FileUpload fileUpload, File file) throws com.mxx.common.exception.IOException {
        try (FileChannel inputChannel = new FileInputStream(fileUpload.getFile()).getChannel();
             FileChannel outputChannel = new FileOutputStream(file).getChannel()) {
            outputChannel.transferFrom(inputChannel, 0, inputChannel.size());

        } catch (IOException ex) {
            throw new com.mxx.common.exception.IOException("write fileUpload.content() to file exception", ex);
        }
    }

    public static void write(FileUpload fileUpload, OutputStream outputStream) throws com.mxx.common.exception.IOException {
        try {
            ByteBuf content = fileUpload.content();
            content.readBytes(outputStream, content.readableBytes());
            outputStream.flush();
            outputStream.close();
            content.clear();
        } catch (IOException ex) {
            throw new com.mxx.common.exception.IOException("write fileUpload.content() exception", ex);
        }

    }

    public static InputStream read(FileUpload fileUpload) {
        UnpooledHeapByteBuf content = (UnpooledHeapByteBuf) fileUpload.content();
        InputStream inputStream = new ByteBufInputStream(content);
        return inputStream;
    }
}
